package cn.fl.sue.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cmm.comm.facade.upload.condition.SysUlDatCfgQueryCondition;
import cmm.mid.core.framework.page.KeyValueVO;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.fl.capital.vo.CapFundIntoLogVO;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.constant.PrjPrdDtlConstant;
import cn.fl.sue.api.ISueApplyDtlApiService;
import cn.fl.sue.api.ISysFlowSSueHApiService;
import cn.fl.sue.condition.SueBscInfoQC;
import cn.fl.sue.condition.SueFileInfoQC;
import cn.fl.sue.condition.SysFlowSSueHQC;
import cn.fl.sue.constant.SueConstant;
import cn.fl.sue.dto.SysFlowSSueHDTO;
import cn.fl.sue.service.ISueApplyInfoService;
import cn.fl.sue.service.ISueBscInfoService;
import cn.fl.sue.service.ISueDtlInfoService;
import cn.fl.sue.vo.*;
import cn.fl.sue.voTransform.SueApplyInfoVOTransform;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.vo.SysUlDatCfgDtlVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.fl.framework.base.context.CurrentThreadContext;

import cn.fl.system.constant.SysLogConstant;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;

import static com.lionbridge.activiti.util.DateUtils.sdf;

/**
 * @Description: 诉讼信息表 控制层
 */
@Controller
@RequestMapping("/sue/sueBscInfo")
public class SueBscInfoController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(SueBscInfoController.class);

    /**
     * SueBscInfo 服务层BEAN
     */
    @Autowired
    private ISueBscInfoService sueBscInfoService;

    /**
     * 文件上传的服务
     */
    @Autowired
    private ISysUlFilesRecService sysUlFilesRecService;

    /**
     * 诉讼信息的服务
     */
    @Autowired
    private ISueApplyInfoService sueApplyInfoService;

    /**
     * 诉讼支付表服务
     */
    @Autowired
    private ISueDtlInfoService sueDtlInfoService;

    @Autowired
    private ISysFlowSSueHApiService sysFlowSSueHApiService;

    /**
     * 到列表页面
     */
    @RequestMapping(value = "/toListPage.do", method = {RequestMethod.GET})
    public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
        String addFlag = request.getParameter("addFlag");
        // 诉讼申请id
        String applyId = request.getParameter("applyId");
        ModelAndView view = new ModelAndView("sue/sueBscInfo/sueBscInfoList");
        BaseLogUtils.info(logger, "toListPage", "跳转到列表页面." + CurrentThreadContext.getCurrentUserName());
        view.addObject("addFlag", addFlag);
        view.addObject("applyId", applyId);
        return view;
    }

    /**
     * 到新的诉讼及结案审批流程附加信息诉讼记录页面
     */
    @RequestMapping(value = "/toNewFlowListPage.do", method = {RequestMethod.GET})
    public ModelAndView toNewFlowListPage(HttpServletRequest request, HttpServletResponse response) {
        String addFlag = request.getParameter("addFlag");
        // 诉讼申请id
        String applyId = request.getParameter("applyId");
        // 诉讼申请id
        String taskFlag = request.getParameter("taskFlag");
        ModelAndView view = new ModelAndView("sue/sueBscInfo/toNewFlowListPage");
        BaseLogUtils.info(logger, "toListPage", "跳转到列表页面." + CurrentThreadContext.getCurrentUserName());
        view.addObject("taskFlag", taskFlag);
        view.addObject("addFlag", addFlag);
        view.addObject("applyId", applyId);
        return view;
    }

    /**
     * 到新增页面
     */
    @RequestMapping(value = "/toAddPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
        BaseLogUtils.info(logger, "toAddPage", "加载SueBscInfo Add页面.", CurrentThreadContext.getCurrentUserName());
        ModelAndView mav = new ModelAndView("sue/sueBscInfo/sueBscInfoAdd");
        // 诉讼申请id
        String applyId = request.getParameter("applyId");
        // 新流程的任务flag（为了隐藏结案审批按钮）
        String taskFlag = request.getParameter("taskFlag");
        // 诉讼进度
        List<KeyValueVO> sueProgress = sueBscInfoService.searchCdList(DictionaryConstant.CODE_SUE_PROGRESS);
        // 判决结果
        List<KeyValueVO> sueRes = sueBscInfoService.searchCdList(DictionaryConstant.CODE_JUDGE_RES);
        // 结案状态
        List<KeyValueVO> caseRes = sueBscInfoService.searchCdList(DictionaryConstant.CODE_CASE_RES);
        // 日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        SueBscInfoQC condition = new SueBscInfoQC();
        condition.setApplyId(Long.valueOf(applyId));
        // 查询全部诉讼记录
        List<SueBscInfoVO> sueBscInfoVOList = sueBscInfoService.searchList(condition);
        SueBscInfoVO sue = null;
        if (CollectionUtils.isNotEmpty(sueBscInfoVOList)) {
            // sue = new SueBscInfoVO();
            for (SueBscInfoVO vo : sueBscInfoVOList) {
                if (SueConstant.SUE_BSC_INFO_PROCESS_CD_SECOND.equals(vo.getProcessCd())) {
                    // 存在二审上诉的诉讼记录的话
                    sue = vo;
                }
            }
            if (sue == null) {
                sue = sueBscInfoVOList.get(sueBscInfoVOList.size()-1);
            }
        }

        mav.addObject("sue", sue);
        if (null != sue) {
            mav.addObject("regisTm", sdf.format(sue.getRegistTm()));
        }
        mav.addObject("id", sueBscInfoService.getSueBscInfoSeq());
        mav.addObject("applyId", applyId);
        mav.addObject("taskFlag", taskFlag);
        mav.addObject("sueProgress", sueProgress);
        mav.addObject("sueRes", sueRes);
        mav.addObject("caseRes", caseRes);
        mav.addObject("caseResJSON", JSON.toJSONString(caseRes));
        mav.addObject("crtTm", sdf.format(new Date()));
        mav.addObject("crtUsrNm", CurrentThreadContext.getCurrentUserName());
        return mav;
    }

    /**
     * 到修改页面
     */
    @RequestMapping(value = "/toModifyPage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        ModelAndView view = new ModelAndView("temp/sueBscInfo/modify");
        view.addObject("id", id);
        BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        return view;
    }

    /**
     * 到查看诉讼资料页面
     */
    @RequestMapping(value = "/toSueFilePage.do", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView toSueFilePage(HttpServletRequest request) {
        String id = request.getParameter("id");
        String tableNm = request.getParameter("tableNm");
        ModelAndView view = new ModelAndView("sue/sueBscInfo/sueFilePage");
        view.addObject("id", id);
        view.addObject("tableNm", tableNm);
        BaseLogUtils.info(logger, "toSueFilePage", "跳转到查看诉讼记录资料页面.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        return view;
    }
    /**
     * 到查看诉讼记录详情页面
     */
    @RequestMapping(value = "/toSueDetail.do", method = {RequestMethod.GET})
    public ModelAndView toSueDetail(HttpServletRequest request) {
        String id = request.getParameter("id");
        String applyId = request.getParameter("applyId");
        SueBscInfoVO sueBscInfoVO = sueBscInfoService.selectById(Long.valueOf(id));

        ModelAndView mv = new ModelAndView("sue/sueBscInfo/sueBscInfoDetail");
        mv.addObject("sue", sueBscInfoVO);
        if (null != sueBscInfoVO) {
            mv.addObject("regisTm", sdf.format(sueBscInfoVO.getRegistTm()));
        }
        // 诉讼进度
        List<KeyValueVO> sueProgressList = sueBscInfoService.searchCdList(DictionaryConstant.CODE_SUE_PROGRESS);
        String sueProgress = "";
        for(KeyValueVO sueProgress_kv:sueProgressList){
            if(sueProgress_kv.getKey().equals(sueBscInfoVO.getProcessCd())){
                sueProgress = sueProgress_kv.getValue();
            }
        }
        // 判决结果
        List<KeyValueVO> sueResList = sueBscInfoService.searchCdList(DictionaryConstant.CODE_JUDGE_RES);
        String judgeRstCd = "";
        for(KeyValueVO judgeRstCd_kv:sueResList){
            if(judgeRstCd_kv.getKey().equals(sueBscInfoVO.getJudgeRstCd())){
                judgeRstCd = judgeRstCd_kv.getValue();
            }
        }
        // 结案状态
        List<KeyValueVO> caseResList = sueBscInfoService.searchCdList(DictionaryConstant.CODE_CASE_RES);
        String caseRes = "";
        for(KeyValueVO caseRes_kv:caseResList){
            if(caseRes_kv.getKey().equals(sueBscInfoVO.getCaseRstCd())){
                caseRes = caseRes_kv.getValue();
            }
        }
        mv.addObject("id", id);
        mv.addObject("applyId", applyId);
        mv.addObject("sueProgress", sueProgress);
        mv.addObject("judgeRstCd", judgeRstCd);
        mv.addObject("caseRes", caseRes);
        BaseLogUtils.info(logger, "toSueFilePage", "跳转到查看诉讼记录详情页面.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        return mv;
    }


    /**
     * 初始化列表
     */
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initList(HttpServletRequest request, HttpServletResponse response) {
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        String applyId = request.getParameter("applyId");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }

        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        SueBscInfoQC qc = new SueBscInfoQC();
        List<SueBscInfoVO> list = null;
        ListPageVO<SueBscInfoVO> listPage = null;
        if (StringUtils.isNotEmpty(applyId) && !"null".equals(applyId)) {
            qc.setApplyId(Long.valueOf(applyId));
            page.setCondition(qc);
            page = this.sueBscInfoService.searchListPage(page);
            list = (List<SueBscInfoVO>) page.getResultList();
            listPage = new ListPageVO<SueBscInfoVO>(list, page.getTotalCount());
        } else {
            list = new ArrayList<>();
            listPage = new ListPageVO<SueBscInfoVO>(list, page.getTotalCount());
        }

        BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
        return listPage;
    }

    /**
     * 删除数据
     */
    @RequestMapping(value = "/removeById.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            return result;
        }
        try {
            this.sueBscInfoService.removeById(Long.valueOf(id));
            BaseLogUtils.info(logger, "removeById", "删除数据.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "removeById", "删除数据失败.[id=" + id + "]" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "removeById", "删除数据失败.[id=" + id + "]" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }

        return result;
    }

    /**
     * 得到一条记录
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getById.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }

        try {
            SueBscInfoVO vo = this.sueBscInfoService.selectById(Long.valueOf(id));
            if (null == vo) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
                BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            }
            result.setData(vo);
            BaseLogUtils.info(logger, "getById", "获取数据.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "getById", "获取失败.[id=" + id + "]" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "getById", "获取失败.[id=" + id + "]" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * 新增
     */
    @RequestMapping(value = "/add.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
        Map<String, Object> entitys = null;
        SueBscInfoVO sueBscInfoVO = null;
        List<SueDtlInfoVO> sueDtlInfoVOS = null;
        SueApplyInfoVO sueApplyInfoVO = null;
        try {
            entitys = this.getEntitysForSueBscInfo(request);
            sueBscInfoVO = (SueBscInfoVO) entitys.get("sueBscInfo");
            if (null != sueBscInfoVO) {
                this.sueBscInfoService.add(sueBscInfoVO);
            }
            sueDtlInfoVOS = (List<SueDtlInfoVO>) entitys.get("sueDtlInfoVOS");
            if (CollectionUtils.isNotEmpty(sueDtlInfoVOS)) {
                this.sueDtlInfoService.addAll(sueDtlInfoVOS);
            }
            sueApplyInfoVO = (SueApplyInfoVO) entitys.get("sueApplyInfoVO");
            if (null != sueApplyInfoVO) {
                this.sueApplyInfoService.modify(SueApplyInfoVOTransform.toDTO(sueApplyInfoVO));
            }
            result.setData(sueBscInfoVO.getId());
            BaseLogUtils.info(logger, "add", "新增数据.[id=" + sueBscInfoVO.getId() + "] DATA:" + JSONObject.toJSONString(sueBscInfoVO), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(sueBscInfoVO) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(sueBscInfoVO) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }

        return result;
    }

    /**
     * 初始化诉讼记录资料grid
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/initSueBscInfoFileCfgGrid.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initSueBscInfoFileCfgGrid(HttpServletRequest request) {
        String id = request.getParameter("id");
        SueFileInfoQC condition = new SueFileInfoQC();
        condition.setSueId(Long.valueOf(id));
        condition.setOrgCd(SueConstant.DEFAULT_ORG_CD);
        condition.setSysCd(SueConstant.FL_SYS_CD);
        List<String> cfgCdList = new ArrayList<>();
        cfgCdList.add(SueConstant.SUE_BSC_INFO_UPLOAD_CFG_CD);
        condition.setCfgCdList(cfgCdList);

        List<SueFileVO> list = this.sueBscInfoService.searchSueFileCfgDtlAndFileCfg(condition);
        // SueBscInfoVO sueBscInfoVO = sueBscInfoService.selectById(Long.valueOf(id));

        BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
        if (CollectionUtils.isNotEmpty(list)) {
            return new ListPageVO<SueFileVO>(list, list.size());
        } else {
            return new ListPageVO<SueFileVO>();
        }
    }

    /**
     * 修改
     */
    @RequestMapping(value = "/modify.do", method = {RequestMethod.POST})
    @ResponseBody
    public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
        if (StringUtils.isEmpty(id)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id=" + id + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        SueBscInfoVO entity = null;
        try {
            entity = new SueBscInfoVO();
            entity.setId(Long.valueOf(id));
            //entity.setName(name);
            boolean success = this.sueBscInfoService.modify(entity);
            if (!success) {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
                BaseLogUtils.info(logger, "modify", "修改失败.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
            }
            BaseLogUtils.info(logger, "modify", "修改成功.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "modify", "修改失败.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
            BaseLogUtils.error(logger, "modify", "修改失败.[id=" + id + "] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return result;
    }

    /**
     * @return
     * @Author huangkailun
     * @Date 15:34 2019-03-04
     * @Description 获取当前诉讼项目的全部支付表信息
     * @Param
     */
    @RequestMapping(value = "/initSuePayDtl.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object initSuePayDtl(HttpServletRequest request) throws BaseException {
        String applyId = request.getParameter("applyId");
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }
        ListPageVO<SueApplyViewDtlVO> listPage = null;
        try {
            // 诉讼信息
            SueApplyInfoVO vo = this.sueApplyInfoService.selectById(Long.valueOf(applyId));
            if (null == vo) {
                BaseLogUtils.info(logger, "initSuePayDtl", "获取数据,数据不存在.[id=" + applyId + "]", CurrentThreadContext.getCurrentUserName());
                return listPage;
            }
            Long id = vo.getDataId();
            String tableNm = vo.getDataTable();
            List<SueApplyViewDtlVO> list = sueBscInfoService.selectPaySchList(id, tableNm);
            if (CollectionUtils.isNotEmpty(list)) {
                List<KeyValueVO> prdStsList = sueBscInfoService.searchCdList(PrjPrdDtlConstant.CODE_PRJ_PRD_STS_CD);
                for (SueApplyViewDtlVO sueDtl : list) {
                    for (KeyValueVO sts : prdStsList) {
                        if (sueDtl.getPrdStsCd().equals(sts.getKey())) {
                            sueDtl.setPrdStsNm(sts.getValue());
                        }
                    }
                }
                listPage = new ListPageVO<SueApplyViewDtlVO>(list, list.size());;
            }
            BaseLogUtils.info(logger, "initSuePayDtl", "获取数据.[id=" + applyId + "]", CurrentThreadContext.getCurrentUserName());
        } catch (BaseException ex) {
            BaseLogUtils.info(logger, "initSuePayDtl", "获取失败.[id=" + applyId + "]" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception ex) {
            BaseLogUtils.error(logger, "initSuePayDtl", "获取失败.[id=" + applyId + "]" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        }
        return listPage;
    }

    /**
     * 发起结案审批流程
     * @param request
     * @return
     */
    @RequestMapping(value = "/startCaseFinishedFlow.do", method = {RequestMethod.GET})
    @ResponseBody
    public Object startCaseFinishedFlow(HttpServletRequest request) {
        // 诉讼申请的id
        String applyId = request.getParameter("applyId");
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
        if (StringUtils.isEmpty(applyId)) {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
            BaseLogUtils.info(logger, "startCaseFinishedFlow", "发起结案审批流程失败,主键不存在.[applyId=" + applyId + "]", CurrentThreadContext.getCurrentUserName());
            return result;
        }
        /**
         * 先做校验：对应的业务编号下的诉讼记录必须审核通过，且无结案流程或结案流程不通过。
         */
        SysFlowSSueHQC sysFlowSSueHQC = new SysFlowSSueHQC();
        sysFlowSSueHQC.setDataId(Long.valueOf(applyId));
        sysFlowSSueHQC.setBusType(SueConstant.SUE_APPLY_TYP_061);
        sysFlowSSueHQC.setAudStsCd(SueConstant.AUD_STS_CD_2);
        // 当前诉讼编号下是否有诉讼申请流程且审核通过
        List<SysFlowSSueHDTO> sueApplyFlowPassList = this.sysFlowSSueHApiService.selectList(sysFlowSSueHQC);
        if (CollectionUtils.isNotEmpty(sueApplyFlowPassList)) {
            sysFlowSSueHQC = new SysFlowSSueHQC();
            List<String> audStsCdList = Lists.newArrayList();
            audStsCdList.add(SueConstant.AUD_STS_CD_1);
            audStsCdList.add(SueConstant.AUD_STS_CD_2);
            sysFlowSSueHQC.setDataId(Long.valueOf(applyId));
            sysFlowSSueHQC.setBusType(SueConstant.SUE_CASE_FINISHED_TYP);
            // 是否有审核中或审核通过的结案审批流程
            List<SysFlowSSueHDTO> closeCaseFlowList = this.sysFlowSSueHApiService.selectList(sysFlowSSueHQC);
            if (CollectionUtils.isEmpty(closeCaseFlowList)) {
                SueApplyInfoVO sueApplyInfoVO = null;
                FlowStartParamsDTO dto = null;
                try {
                    sueApplyInfoVO = sueApplyInfoService.selectById(Long.valueOf(applyId));
                    if (null == sueApplyInfoVO) {
                        result.setSuccess(BaseConstant.IS_YESNO_NO);
                        result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
                        BaseLogUtils.info(logger, "startCaseFinishedFlow", "发起结案审批流程失败.[applyId=" + applyId + "] DATA:" + JSONObject.toJSONString(sueApplyInfoVO), CurrentThreadContext.getCurrentUserName());
                        return result;
                    }
                    // 申请人的组织架构
                    String orgCd = sueApplyInfoVO.getApplyerOrgCd();
                    // 申请人的事业部组织架构
                    String buOrgCd = null;
                    if (SueConstant.DEFAULT_ORG_CD.equals(orgCd)) {
                        buOrgCd = orgCd;
                    } else {
                        buOrgCd = orgCd.substring(0, 8);
                    }
                    dto = sueApplyInfoService.getFlowStartParamsDTO(orgCd, buOrgCd, SueConstant.SUE_CASE_FINISHED_TYP, Long.valueOf(applyId), SueConstant.SUE_DATA_TABLE_NM);
                    sueBscInfoService.startCaseFinishedFlow(dto);
                    BaseLogUtils.info(logger, "startCaseFinishedFlow", "发起结案审批流程成功.[applyId=" + applyId + "] DATA:" + JSONObject.toJSONString(sueApplyInfoVO), CurrentThreadContext.getCurrentUserName());
                } catch (BaseException ex) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo(ex.getMessage());
                    BaseLogUtils.info(logger, "startCaseFinishedFlow", "发起结案审批流程失败.[applyId=" + applyId + "] DATA:" + JSONObject.toJSONString(sueApplyInfoVO) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
                } catch (Exception ex) {
                    result.setSuccess(BaseConstant.IS_YESNO_NO);
                    result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
                    BaseLogUtils.error(logger, "startCaseFinishedFlow", "修改失败.[id=" + applyId + "] DATA:" + JSONObject.toJSONString(sueApplyInfoVO) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
                }
            } else {
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo("当前诉讼编号下存在审核中或审核通过的结案审批流程，无法发起新的结案审批流程");
            }
        } else {
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("当前诉讼编号下无诉讼申请流程或有诉讼申请流程正在审核中，无法发起结案审批流程");
        }
        return result;
    }

    /**
     * 获取请求参数
     *
     * @param request 请求
     * @return
     */
    private Map<String, Object> getEntitysForSueBscInfo(HttpServletRequest request) throws BaseException {
        Map<String, Object> entitys = new HashMap<String, Object>();
        /**
         * 获取诉讼记录信息参数
         */
        //主键
        String id = request.getParameter("id");
        // 诉讼进度
        String sueProgress = request.getParameter("sueProgress");
        // 判决结果
        String judgeRstCd = request.getParameter("judgeRstCd");
        // 调解结果
        String mediationResult = request.getParameter("mediationResult");
        // 案件编号
        String caseNo = request.getParameter("caseNo");
        // 开庭时间
        String courtTm = request.getParameter("courtTm");
        // 管辖法院
        String courtNm = request.getParameter("courtNm");
        // 立案时间
        String registTm = request.getParameter("registTm");
        // 判决时间
        String judgeTm = request.getParameter("judgeTm");
        // 生效开始时间
        String effectStDt = request.getParameter("effectStDt");
        // 生效结束时间
        String effectEdDt = request.getParameter("effectEdDt");
        // 结案状态
        String caseRes = request.getParameter("caseRes");
        // 其他说明
        String sueRem = request.getParameter("sueRem");
        // 诉讼申请id
        String applyId = request.getParameter("applyId");
        //庭审法官
        String judgeName = request.getParameter("judgeName");
        //庭审法官手机号
        String judgeTel = request.getParameter("judgeTel");
        //书记员名称
        String clerkName = request.getParameter("clerkName");
        //书记员手机号
        String clerkTel = request.getParameter("clerkTel");
        //执行法官名称
        String execJudgeName = request.getParameter("execJudgeName");
        //执行法官手机号
        String execJudgeTel = request.getParameter("execJudgeTel");


        //验证参数并赋值
        SueBscInfoVO entity = new SueBscInfoVO();

        if (StringUtils.isNotBlank(id)) {
            entity.setId(Long.valueOf(id));
        }
        if (StringUtils.isNotBlank(sueProgress)) {
            entity.setProcessCd(sueProgress);
        }
        if (StringUtils.isNotBlank(judgeRstCd)) {
            entity.setJudgeRstCd(judgeRstCd);
        }
        if (StringUtils.isNotBlank(mediationResult)) {
            entity.setMediationResult(mediationResult);
        }
        if (StringUtils.isNotBlank(caseNo)) {
            entity.setCaseNo(caseNo);
        }
        if (StringUtils.isNotBlank(courtTm)) {
            entity.setCourtTm(DateUtils.formatStringToDate(courtTm, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotBlank(courtNm)) {
            entity.setCourtNm(courtNm);
        }
        if (StringUtils.isNotBlank(registTm)) {
            entity.setRegistTm(DateUtils.formatStringToDate(registTm, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotBlank(judgeTm)) {
            entity.setJudgeTm(DateUtils.formatStringToDate(judgeTm, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotBlank(effectStDt)) {
            entity.setEffectStTm(DateUtils.formatStringToDate(effectStDt, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotBlank(effectEdDt)) {
            entity.setEffectEdTm(DateUtils.formatStringToDate(effectEdDt, DateUtils.YYYY_MM_DD));
        }
        if (StringUtils.isNotBlank(caseRes)) {
            entity.setCaseRstCd(caseRes);
        }
        if (StringUtils.isNotBlank(sueRem)) {
            entity.setSueRem(sueRem);
        }
        if (StringUtils.isNotBlank(applyId)) {
            entity.setApplyId(Long.valueOf(applyId));
        }
        if (StringUtils.isNotBlank(judgeName)) {
            entity.setJudgeName(judgeName);
        }
        if (StringUtils.isNotBlank(judgeTel)) {
            entity.setJudgeTel(judgeTel);
        }
        if (StringUtils.isNotBlank(clerkName)) {
            entity.setClerkName(clerkName);
        }
        if (StringUtils.isNotBlank(clerkTel)) {
            entity.setClerkTel(clerkTel);
        }
        if (StringUtils.isNotBlank(execJudgeName)) {
            entity.setExecJudgeName(execJudgeName);
        }
        if (StringUtils.isNotBlank(execJudgeTel)) {
            entity.setExecJudgeTel(execJudgeTel);
        }

        Date tm = new Date();
        entity.setId(Long.valueOf(id));
        entity.setMdfTm(tm);
        entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
        entity.setCrtTm(tm);
        entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
        entity.setCrtUsrNm(CurrentThreadContext.getCurrentUserName());

        entitys.put("sueBscInfo", entity);

        /**
         * 诉讼支付表数据
         */

        String paySchData = request.getParameter("paySchData");
        JSONArray arr = JSON.parseArray(paySchData);
        List<SueDtlInfoVO> sueDtlInfoVOS = null;

        if (arr.size() != 0) {
            sueDtlInfoVOS = new ArrayList<>();
            for (Object obj : arr) {
                SueDtlInfoVO sueDtlInfoVO = new SueDtlInfoVO();
                JSONObject json = (JSONObject) obj;
                sueDtlInfoVO.setPaySchId(json.getLong("paySchId"));
                sueDtlInfoVO.setSueId(Long.valueOf(id));
                sueDtlInfoVO.setTableNm(json.getString("tableNm"));
                sueDtlInfoVO.setJudgeResult(json.getString("judgeResult"));
                sueDtlInfoVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
                sueDtlInfoVO.setCrtTm(new Date());
                sueDtlInfoVOS.add(sueDtlInfoVO);
            }
        }
        entitys.put("sueDtlInfoVOS", sueDtlInfoVOS);

        /**
         * 修改诉讼申请表的冗余案件编号和立案时间
         */
        SueApplyInfoVO sueApplyInfoVO = sueApplyInfoService.selectById(Long.valueOf(applyId));

        sueApplyInfoVO.setId(Long.valueOf(applyId));

        SueBscInfoQC qc = new SueBscInfoQC();
        qc.setApplyId(Long.valueOf(applyId));
        List<SueBscInfoVO> sueBscInfoVOList = this.sueBscInfoService.searchList(qc);
        if (CollectionUtils.isNotEmpty(sueBscInfoVOList)) {
            if (StringUtils.isEmpty(sueApplyInfoVO.getCaseNo()) && null == sueApplyInfoVO.getRegistTm()) {
                sueApplyInfoVO.setCaseNo(sueBscInfoVOList.get(0).getCaseNo());
                sueApplyInfoVO.setRegistTm(sueBscInfoVOList.get(0).getRegistTm());
            }
            if (StringUtils.isEmpty(sueApplyInfoVO.getCaseNo2()) && null == sueApplyInfoVO.getRegistTm2()) {
                for (SueBscInfoVO vo : sueBscInfoVOList) {
                    if (SueConstant.SUE_BSC_INFO_PROCESS_CD_SECOND.equals(vo.getProcessCd())) {
                        sueApplyInfoVO.setCaseNo2(vo.getCaseNo());
                        sueApplyInfoVO.setRegistTm2(vo.getRegistTm());
                        break;
                    }
                }
            }
        } else {
            sueApplyInfoVO.setCaseNo(caseNo);
            sueApplyInfoVO.setRegistTm(DateUtils.formatStringToDate(registTm, DateUtils.YYYY_MM_DD));
        }

        // 诉讼进度选择“已立案、已开庭、上诉二审、已判决、已调解、已申请执行”情况下：诉讼状态为“诉讼中”；
        if (SueConstant.SUE_BSC_INFO_ON_CASE.equals(sueProgress) || SueConstant.SUE_BSC_INFO_ON_COURT.equals(sueProgress) || SueConstant.SUE_BSC_INFO_PROCESS_CD_SECOND.equals(sueProgress)
                || SueConstant.SUE_BSC_INFO_JUDGED.equals(sueProgress) || SueConstant.SUE_BSC_INFO_MEDIATED.equals(sueProgress) || SueConstant.SUE_BSC_INFO_APPLY_DO.equals(sueProgress)) {
            sueApplyInfoVO.setSueStsCd(SueConstant.ON_SUE);
        }

        entitys.put("sueApplyInfoVO", sueApplyInfoVO);
        return entitys;
    }

    /**
     * 在文件接收SYS_UL_FILE_REC表中增加文件上传记录
     *
     * @param request
     */
    @RequestMapping(value = "/uploadSueBscInfoFile.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Object uploadSueBscInfoFile(HttpServletRequest request) {
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
        String fileParams = request.getParameter("fileParams");
        String cfgCd = request.getParameter("cfgCd");
        String cfgDtlCd = request.getParameter("cfgDtlCd");
        String orgCd = request.getParameter("orgCd");
        String id = request.getParameter("id");
        if (StringUtils.isBlank(id)) {
            BaseLogUtils.error(logger, "uploadSueBscInfoFile", "上传项目资料文件失败,主键ID为空-->cfgCd=" + cfgCd + ",cfgDtlCd=" + cfgDtlCd + ",orgCd=" + orgCd);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
        } else {
            boolean flag = this.sysUlFilesRecService.addAttchmnt(id, fileParams, cfgCd, cfgDtlCd, "SUE_BSC_INFO", null, null, null, false, orgCd);
            if (!flag) {
                BaseLogUtils.error(logger, "uploadSueBscInfoFile", "上传诉讼记录资料文件失败-->Id=" + id + ",cfgCd=" + cfgCd + ",cfgDtlCd=" + cfgDtlCd + ",file=" + fileParams);
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(SysLogConstant.LOG_FILE_UPLOAD_FAIL);
                return result;
            }
            BaseLogUtils.info(logger, "uploadSueBscInfoFile", "上传诉讼记录资料文件成功-->Id=" + id + ",cfgCd=" + cfgCd + ",cfgDtlCd=" + cfgDtlCd + ",orgCd=" + orgCd);
        }
        return result;
    }

}

